﻿using System;
using System.Collections.Generic;
using System.Text;
using Common;
using Common.Model;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using NLog;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using NLog.Web;
using ConsoleService.Helps;
using ConsoleService.Cache;

namespace ConsoleService.Services
{
    public class MQService
    {
        private readonly EmailServices _emailServices;
        public MQService(EmailServices emailServices)
        {
            _emailServices = emailServices;
        }

        Logger logger = LogManager.GetCurrentClassLogger();
        public void InitLog()
        {
            NLog.Web.NLogBuilder.ConfigureNLog("nlog.config");
        }
        /// <summary>
        /// 运行队列
        /// </summary>
        public void Run()
        {
            logger.Warn("消息队列开始运行....");

            ReadQueue();

            readEmailQueue();

            CommonDelayConsumerMessage();
        }

        /// <summary>
        /// 读取邮件队列信息
        /// </summary>
        public void readEmailQueue()
        {
            try
            {
                var connection = RabbitMQUtil.FACTORY.CreateConnection();
                var channel = connection.CreateModel();
                channel.QueueDeclare("emailQueue", true, false, false, null);
                channel.BasicQos(0, 1, false);
                var consumer = new EventingBasicConsumer(channel);
                channel.BasicConsume("emailQueue", true, consumer);
                consumer.Received += (model, ea) =>
                {
                    var body = ea.Body;
                    var msg = Encoding.UTF8.GetString(ea.Body.ToArray());
                    string logmsg = string.Format("读取邮件内容： {0} ", msg);
                    InitLog();
                    logger.Warn(logmsg);
                    Console.WriteLine(logmsg);
                    if (!string.IsNullOrEmpty(msg))
                    {
                        var entity = JsonConvert.DeserializeObject<EmailModel>(msg);
                        if (entity != null)
                        {
                            _emailServices.SendEmail(entity);
                        }
                    }
                };
            }
            catch (Exception ex)
            {
                string message = string.Format("读取邮件内容异常： {0} ", ex.Message, ex);
                InitLog();
                logger.Error(message);
                Console.WriteLine(message);
            }
        }



        /// <summary>
        /// 读取即时队列信息
        /// </summary>
        public void ReadQueue()
        {
            try
            {
                var connection = RabbitMQUtil.FACTORY.CreateConnection();
                var channel = connection.CreateModel();
                channel.QueueDeclare("track", true, false, false, null);
                channel.BasicQos(0, 1, false);
                var consumer = new EventingBasicConsumer(channel);
                channel.BasicConsume("track", true, consumer);
                consumer.Received += (model, ea) =>
                {
                    var body = ea.Body;
                    var msg = Encoding.UTF8.GetString(ea.Body.ToArray());
                    string logmsg = string.Format("读取队列消息内容： {0} ", msg);
                    if (!string.IsNullOrEmpty(msg))
                    {

                    }
                    InitLog();
                    logger.Warn(logmsg);
                    Console.WriteLine(logmsg);
                };
            }
            catch (Exception ex)
            {
                string message = string.Format("读取队列异常： {0} ", ex.Message, ex);
                InitLog();
                logger.Error(message);
                Console.WriteLine(message);
            }
        }


        /// <summary>
        /// 读取延迟队列消息
        /// </summary>
        public void CommonDelayConsumerMessage()
        {

            try
            {
                //1、需要下载 rabbitmq_delayed_meaage_exchange 插件，
                //下载地址：https://www.rabbitmq.com/community-plugins.html
                //2、将下载的文件 rabbitmq_delayed_message_exchange-3.8.0.ez放到 rabbitmq_server-3.8.9\plugins 文件夹中
                //3、安装插件：rabbitmq-plugins enable rabbitmq_delayed_message_exchange

                var connection = RabbitMQUtil.FACTORY.CreateConnection();

                var channel = connection.CreateModel();
                Dictionary<string, object> dic = new Dictionary<string, object>();
                dic.Add("x-delayed-type", "direct");
                var exchange = "exchange-direct-delay-common";
                var queue = "lis-delay-quene-common";
                var routingKey = "routingkey-delay-common";
                channel.ExchangeDeclare(exchange: exchange, type: "x-delayed-message", true, false, dic);
                channel.QueueBind(queue: queue, exchange: exchange, routingKey: routingKey);

                //回调，当consumer收到消息后会执行该函数
                var consumer = new EventingBasicConsumer(channel);
                consumer.Received += (model, ea) =>
                {
                    var body = ea.Body;
                    var msg = Encoding.UTF8.GetString(ea.Body.ToArray());
                    string logmsg = string.Format("读取延迟队列： {0} ", msg);
                    InitLog();
                    logger.Warn(logmsg);
                    //Console.WriteLine(logmsg);
                    if (!string.IsNullOrEmpty(msg))
                    {

                        var entity = JsonConvert.DeserializeObject<DelayMessageModel>(msg);
                        if (entity != null && !string.IsNullOrEmpty(entity.JsonData) && WebHelper.IsJsonStart(entity.JsonData))
                        {
                            var result = JsonConvert.DeserializeObject<RequestModel>(entity.JsonData);
                            if (result != null)
                            {
                                var request = WebHelper.HttpRequest(result);
                                var log = $"回调地址请求成功：{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}-{result.WebSide + result.Resources}，{request}";
                                Console.WriteLine(log);
                                InitLog();
                                logger.Warn(log);
                            }
                        }

                        if (entity != null && !string.IsNullOrEmpty(entity.CallBackUrl))
                        {
                            var result = WebHelper.HttpRequest(entity.CallBackUrl);
                            var log = $"回调地址请求成功：{entity.CallBackUrl}，{result}";
                            Console.WriteLine(log);
                            InitLog();
                            logger.Warn(log);
                        }
                    }
                };
                channel.BasicConsume(queue, true, consumer);
            }
            catch (Exception ex)
            {
                string message = string.Format("读取延迟队列异常： {0} ", ex.Message, ex);
                InitLog();
                logger.Error(message);
                Console.WriteLine(message);
            }
        }
    }
}
